package com.kdzy.lshy.common.service;


import com.alibaba.fastjson.JSONObject;
import com.kdzy.lshy.common.common.XunCheng;
import com.kdzy.lshy.common.utils.Base64Tool;
import io.swagger.annotations.ApiParam;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hanrui
 * @since 2018-06-15
 * 身份证信息service
 */

@Service(value = "idcardService")
public class IDCardService {

    @Autowired
    private XunCheng xunCheng;

    /**
     * 获取身份证信息
     * <p>
     * 参数: path 身份证图片URL
     *
     * @return
     */

    public Object getIDcardInfoByPath(

            @ApiParam(
                    required = true,
                    value = "path",
                    name = "path"
            )
                    String path, HttpServletRequest request) {


        String bas64String = Base64Tool.encryptToBase64(path);

        return  invoke(bas64String);

    }


    /**
     * 获取身份证信息
     * <p>
     * 参数: base64String
     * 类型  String
     *
     * @return
     */

    public Object getIDcardInfoByBase64String (

            @ApiParam(
                    required = true,
                    value = "base64String",
                    name = "base64String"
            )
                    String  base64String, HttpServletRequest request) {


        return invoke(base64String);
    }


    public Object invoke(String bas64String){

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(xunCheng.getInterface_ocr());
        List<NameValuePair> kvList = new ArrayList<NameValuePair>();
        kvList.add(new BasicNameValuePair("key", xunCheng.getApiKey()));
        kvList.add(new BasicNameValuePair("bas64String", bas64String));
        kvList.add(new BasicNameValuePair("side", "1"));
        StringEntity entity = null;
        JSONObject id_json = new JSONObject();

        try {
            entity = new UrlEncodedFormEntity(kvList, "utf-8");
            post.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(post);
            String string = EntityUtils.toString(response.getEntity());
            id_json = JSONObject.parseObject(string);
            response.close();
            httpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return id_json;
    }


}
